import numpy as np
import numpy.lib.recfunctions as nprf

def string2dummy(d):
    '''
    Accepts a record array

    Returns a new array with any string fields dropped and dummy 
    variables for the string observations.
    The old string values are the new column headers for these dummies
    
    Creates dummy variables for the string type variables
    for the distinct strings adding it to the original record array using the
    string variables as the new column headers for these dummies.
    
    Notes
    ------
    This makes a dummy variable for EVERY distinct string.  
    When doing fixed effects, etc.
    remember not to fall into the dummy variable trap...

    Should probably do some checking to make sure that the newly 
    created column headers aren't already used or unusable
    '''

    for i in range(len(d.dtype)):
        if d.dtype[i].type is np.string_:
            tmp_arr=np.unique(d.field(i))
            tmp_dummy=(tmp_arr[:,np.newaxis]==d.field(i)).astype(float)
            #tmp_dummy is a (number of dummies x number of observations) array
            d=nprf.drop_fields(d,d.dtype.names[i],usemask=False, asrecarray=True)
            d=nprf.append_fields(d,tmp_arr.strip("\""),data=tmp_dummy,usemask=False,asrecarray=True)
    return d
